#include "bookmarkdialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTreeWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QDialogButtonBox>
#include <QHeaderView>
#include <QTreeWidgetItem>
#include <QDateTime>
#include <QMessageBox>
#include <QFormLayout>
#include <QLabel>
#include <QApplication>
#include <QClipboard>

BookmarkDialog::BookmarkDialog(BookmarkManager *manager, const QString &currentQuery,
                               const QString &currentDatabase, QWidget *parent)
    : QDialog(parent)
    , m_bookmarkManager(manager)
    , m_currentDatabase(currentDatabase)
    , m_selectedBookmarkId(-1)
    , m_editMode(false)
{
    setupUI();
    loadBookmarks();
    
    // 如果提供了当前查询，则填充到表单中
    if (!currentQuery.isEmpty()) {
        m_queryEdit->setPlainText(currentQuery);
    }
    
    // 连接信号和槽
    connect(m_bookmarkManager, &BookmarkManager::bookmarksChanged, this, &BookmarkDialog::loadBookmarks);
}

void BookmarkDialog::loadBookmarks()
{
    QList<BookmarkItem> items = m_bookmarkManager->getBookmarks();
    updateBookmarkList(items);
    resetForm();
}

void BookmarkDialog::searchBookmarks()
{
    QString searchTerm = m_searchEdit->text();
    QList<BookmarkItem> items;
    
    if (searchTerm.isEmpty()) {
        items = m_bookmarkManager->getBookmarks();
    } else {
        items = m_bookmarkManager->searchBookmarks(searchTerm);
    }
    
    updateBookmarkList(items);
}

void BookmarkDialog::addBookmark()
{
    QString name = m_nameEdit->text().trimmed();
    QString query = m_queryEdit->toPlainText().trimmed();
    
    if (name.isEmpty()) {
        QMessageBox::warning(this, tr("Invalid Input"), tr("Please enter a name for the bookmark."));
        return;
    }
    
    if (query.isEmpty()) {
        QMessageBox::warning(this, tr("Invalid Input"), tr("Please enter a SQL query for the bookmark."));
        return;
    }
    
    if (m_bookmarkManager->addBookmark(name, query, m_currentDatabase)) {
        QMessageBox::information(this, tr("Success"), tr("Bookmark added successfully."));
        resetForm();
    } else {
        QMessageBox::warning(this, tr("Error"), tr("Failed to add bookmark."));
    }
}

void BookmarkDialog::editBookmark()
{
    if (m_selectedBookmarkId <= 0) {
        return;
    }
    
    if (!m_editMode) {
        // 进入编辑模式
        BookmarkItem item = m_bookmarkManager->getBookmarkById(m_selectedBookmarkId);
        if (item.id > 0) {
            m_nameEdit->setText(item.name);
            m_queryEdit->setPlainText(item.query);
            m_editMode = true;
            m_editButton->setText(tr("Update Bookmark"));
        }
    } else {
        // 执行更新
        QString name = m_nameEdit->text().trimmed();
        QString query = m_queryEdit->toPlainText().trimmed();
        
        if (name.isEmpty()) {
            QMessageBox::warning(this, tr("Invalid Input"), tr("Please enter a name for the bookmark."));
            return;
        }
        
        if (query.isEmpty()) {
            QMessageBox::warning(this, tr("Invalid Input"), tr("Please enter a SQL query for the bookmark."));
            return;
        }
        
        if (m_bookmarkManager->updateBookmark(m_selectedBookmarkId, name, query)) {
            QMessageBox::information(this, tr("Success"), tr("Bookmark updated successfully."));
            m_editMode = false;
            m_editButton->setText(tr("Edit Bookmark"));
            resetForm();
        } else {
            QMessageBox::warning(this, tr("Error"), tr("Failed to update bookmark."));
        }
    }
}

void BookmarkDialog::removeBookmark()
{
    if (m_selectedBookmarkId <= 0) {
        return;
    }
    
    int result = QMessageBox::question(this, tr("Confirm Removal"), 
                                      tr("Are you sure you want to remove this bookmark?"));
    
    if (result == QMessageBox::Yes) {
        if (m_bookmarkManager->removeBookmark(m_selectedBookmarkId)) {
            QMessageBox::information(this, tr("Success"), tr("Bookmark removed successfully."));
            resetForm();
        } else {
            QMessageBox::warning(this, tr("Error"), tr("Failed to remove bookmark."));
        }
    }
}

void BookmarkDialog::onItemDoubleClicked()
{
    useSelectedQuery();
}

void BookmarkDialog::onItemSelected()
{
    QList<QTreeWidgetItem *> selectedItems = m_bookmarkTree->selectedItems();
    
    if (!selectedItems.isEmpty()) {
        QTreeWidgetItem *item = selectedItems.first();
        m_selectedBookmarkId = item->data(0, Qt::UserRole).toInt();
        m_selectedQuery = item->data(0, Qt::UserRole + 1).toString();
        
        m_useButton->setEnabled(true);
        m_editButton->setEnabled(true);
        m_removeButton->setEnabled(true);
    } else {
        m_selectedBookmarkId = -1;
        m_selectedQuery.clear();
        m_useButton->setEnabled(false);
        m_editButton->setEnabled(false);
        m_removeButton->setEnabled(false);
    }
}

void BookmarkDialog::useSelectedQuery()
{
    if (!m_selectedQuery.isEmpty()) {
        emit querySelected(m_selectedQuery);
        accept();
    }
}

void BookmarkDialog::clearAllBookmarks()
{
    int result = QMessageBox::question(this, tr("Confirm Clear"), 
                                      tr("Are you sure you want to remove all bookmarks?"));
    
    if (result == QMessageBox::Yes) {
        if (m_bookmarkManager->clearAllBookmarks()) {
            QMessageBox::information(this, tr("Success"), tr("All bookmarks cleared successfully."));
            resetForm();
        } else {
            QMessageBox::warning(this, tr("Error"), tr("Failed to clear bookmarks."));
        }
    }
}

void BookmarkDialog::setupUI()
{
    setWindowTitle(tr("SQL Bookmarks"));
    setModal(true);
    resize(900, 600);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 上半部分：书签列表和搜索
    QHBoxLayout *topLayout = new QHBoxLayout;
    
    // 搜索框
    QVBoxLayout *searchLayout = new QVBoxLayout;
    searchLayout->setContentsMargins(0, 0, 0, 0);
    
    QHBoxLayout *searchEditLayout = new QHBoxLayout;
    m_searchEdit = new QLineEdit;
    m_searchEdit->setPlaceholderText(tr("Search bookmarks..."));
    connect(m_searchEdit, &QLineEdit::textChanged, this, &BookmarkDialog::searchBookmarks);
    
    QPushButton *searchButton = new QPushButton(tr("Search"));
    connect(searchButton, &QPushButton::clicked, this, &BookmarkDialog::searchBookmarks);
    
    searchEditLayout->addWidget(m_searchEdit);
    searchEditLayout->addWidget(searchButton);
    searchLayout->addLayout(searchEditLayout);
    
    // 书签树
    m_bookmarkTree = new QTreeWidget;
    m_bookmarkTree->setHeaderLabels({tr("Name"), tr("Query"), tr("Database"), tr("Created")});
    m_bookmarkTree->setColumnWidth(0, 150);
    m_bookmarkTree->setColumnWidth(1, 300);
    m_bookmarkTree->setColumnWidth(2, 100);
    m_bookmarkTree->setColumnWidth(3, 150);
    m_bookmarkTree->setRootIsDecorated(false);
    m_bookmarkTree->setAlternatingRowColors(true);
    m_bookmarkTree->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_bookmarkTree->setSelectionMode(QAbstractItemView::SingleSelection);
    
    connect(m_bookmarkTree, &QTreeWidget::itemDoubleClicked, this, &BookmarkDialog::onItemDoubleClicked);
    connect(m_bookmarkTree, &QTreeWidget::itemSelectionChanged, this, &BookmarkDialog::onItemSelected);
    
    searchLayout->addWidget(m_bookmarkTree);
    
    topLayout->addLayout(searchLayout, 3);
    
    // 按钮区域
    QVBoxLayout *buttonLayout = new QVBoxLayout;
    buttonLayout->setContentsMargins(0, 0, 0, 0);
    
    m_useButton = new QPushButton(tr("Use Query"));
    m_useButton->setEnabled(false);
    connect(m_useButton, &QPushButton::clicked, this, &BookmarkDialog::useSelectedQuery);
    buttonLayout->addWidget(m_useButton);
    
    QPushButton *copyButton = new QPushButton(tr("Copy Query"));
    connect(copyButton, &QPushButton::clicked, this, [this]() {
        if (!m_selectedQuery.isEmpty()) {
            QApplication::clipboard()->setText(m_selectedQuery);
            QMessageBox::information(this, tr("Copied"), tr("Query copied to clipboard"));
        }
    });
    buttonLayout->addWidget(copyButton);
    
    m_editButton = new QPushButton(tr("Edit Bookmark"));
    m_editButton->setEnabled(false);
    connect(m_editButton, &QPushButton::clicked, this, &BookmarkDialog::editBookmark);
    buttonLayout->addWidget(m_editButton);
    
    m_removeButton = new QPushButton(tr("Remove Bookmark"));
    m_removeButton->setEnabled(false);
    connect(m_removeButton, &QPushButton::clicked, this, &BookmarkDialog::removeBookmark);
    buttonLayout->addWidget(m_removeButton);
    
    m_clearButton = new QPushButton(tr("Clear All"));
    connect(m_clearButton, &QPushButton::clicked, this, &BookmarkDialog::clearAllBookmarks);
    buttonLayout->addWidget(m_clearButton);
    
    buttonLayout->addStretch();
    
    topLayout->addLayout(buttonLayout, 1);
    
    mainLayout->addLayout(topLayout, 3);
    
    // 下半部分：书签编辑表单
    QGroupBox *formGroup = new QGroupBox(tr("Bookmark Details"));
    QVBoxLayout *formLayout = new QVBoxLayout(formGroup);
    
    QFormLayout *detailsForm = new QFormLayout;
    
    m_nameEdit = new QLineEdit;
    m_nameEdit->setPlaceholderText(tr("Enter bookmark name"));
    detailsForm->addRow(tr("Name:"), m_nameEdit);
    
    m_queryEdit = new QTextEdit;
    m_queryEdit->setPlaceholderText(tr("Enter SQL query"));
    m_queryEdit->setMaximumHeight(100);
    detailsForm->addRow(tr("Query:"), m_queryEdit);
    
    formLayout->addLayout(detailsForm);
    
    QHBoxLayout *formButtonLayout = new QHBoxLayout;
    QPushButton *addButton = new QPushButton(tr("Add Bookmark"));
    connect(addButton, &QPushButton::clicked, this, &BookmarkDialog::addBookmark);
    formButtonLayout->addWidget(addButton);
    formButtonLayout->addStretch();
    
    formLayout->addLayout(formButtonLayout);
    
    mainLayout->addWidget(formGroup, 1);
    
    // 底部按钮
    m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
    connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    mainLayout->addWidget(m_buttonBox);
}

void BookmarkDialog::updateBookmarkList(const QList<BookmarkItem> &items)
{
    m_bookmarkTree->clear();
    
    for (const BookmarkItem &item : items) {
        QTreeWidgetItem *treeItem = new QTreeWidgetItem(m_bookmarkTree);
        treeItem->setText(0, item.name);
        
        // 限制显示的查询长度
        QString displayQuery = item.query;
        if (displayQuery.length() > 100) {
            displayQuery = displayQuery.left(100) + "...";
        }
        treeItem->setText(1, displayQuery);
        
        treeItem->setText(2, item.databaseName);
        treeItem->setText(3, item.created.toString("yyyy-MM-dd hh:mm:ss"));
        treeItem->setData(0, Qt::UserRole, item.id);
        treeItem->setData(0, Qt::UserRole + 1, item.query);
    }
    
    m_bookmarkTree->header()->resizeSections(QHeaderView::ResizeToContents);
}

void BookmarkDialog::resetForm()
{
    m_nameEdit->clear();
    m_queryEdit->clear();
    m_selectedBookmarkId = -1;
    m_selectedQuery.clear();
    m_editMode = false;
    m_editButton->setText(tr("Edit Bookmark"));
    m_useButton->setEnabled(false);
    m_editButton->setEnabled(false);
    m_removeButton->setEnabled(false);
    
    // 清除选择
    m_bookmarkTree->clearSelection();
}